const events=require('events');
const {Post,User}=require('../models/index');

module.exports=(verify=true)=>async (ctx,next)=>{
    let {id}=ctx.params,{token}=ctx.query,ee=new events();
    ee.on('invalid',msg=>{
        ctx.body={
            code:400,
            msg
        }
    });

    let [tokenUser,post]=await Promise.all([
        User.findOne({token},{_id:true}),
        Post.findOne({_id:id})
    ]);

    if(!tokenUser)return ee.emit('invalid','Token错误');
    if(!post)return ee.emit('invalid','话题不存在');
    if(true===verify){
        if(tokenUser._id.toString()!==post.author.toString())return ee.emit('invalid','无权限');
    }
    ctx.state={
        id,
        token,
        post,
        tokenUser
    };
    await next();
};